package tacos.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import tacos.domain.Order;
import tacos.domain.User;
import tacos.props.OrderProps;
import tacos.repository.OrderRepository;

import javax.validation.Valid;
import java.security.Principal;

/**
 * 订单表现层
 */
@Slf4j
@Controller
@RequestMapping("/ordersx")
@SessionAttributes("order")
public class OrderController {

//    @ModelAttribute
//    public void TestModelAttribute(Model model) {
//        /**
//         * 测试 当类中含有另一个 ModelAttribute 注解时，请求的参数不会自动匹配并封装bean
//         */
//        System.out.println("model Attribute works");
//    }

    private OrderRepository orderRepo;
    private OrderProps props;

    public OrderController(OrderRepository orderRepo,OrderProps props){
        this.orderRepo = orderRepo;
        this.props = props;
    }

    @GetMapping("current")
    public String orderForm(Model model) {
//        Order order = new Order();
//        order.setName("order Form model Attribute");
//        model.addAttribute("order", order);
        return "orderForm";
    }

    // @ModelAttribute("order")
    // 另外 ModelAttribute("order") 的值会从model属性中获取，如果【类】上没有标注@SessionAttributes("user")，那么scope为request，如果标注了，那么scope为session
    // ModelAttribute 会注册为本次request的属性
    // 如果不写，则会返回类名称的小写 Order -> order 作为默认Model属性
    @PostMapping
    public String processOrder(@Valid Order order, Errors errors, SessionStatus sessionStatus, @AuthenticationPrincipal User user) {
        if (errors.hasErrors()) {
            return "orderForm";
        }

        orderRepo.save(order);
        sessionStatus.setComplete(); // 清空session

        log.info("Order submitted:" + order);
        return "redirect:/";
    }

    @GetMapping
    public String ordersForUser(@AuthenticationPrincipal User user,Model model){
        Pageable pageable = PageRequest.of(0,props.getPageSize());
        model.addAttribute("orders",orderRepo.findByUserOrderByPlacedAtDesc(user,pageable));
        return "orderList";
    }
}
